﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Business;
using AMM.Business.Project;
using AMM.CustomClassLibrary;
using AMM.CustomWinComponents.Validator;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Business;
using AMM.Model.Project;
using AMM.UserControls;

namespace AMM.Forms.Business {
    public partial class FrmPriceEvaluate : FrmPriceEvaluateBase {

        private int _pageIndex;
        private PriceEvaluateSearchModel _searchModel;
        private PriceEvaluateProcessor _priceEvaluateProcessor;
        private List<PriceEvaluateViewModel> _priceEvaluateList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1301"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new PriceEvaluateSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.FBS.CurrentItem = new PriceEvaluate() { ClassStatus = ClassStatus.Added };

            this.gbPriceEvaluateInfo.Enabled = true;
            this.validator.ClearAllControlErrorIcons();
            base.Add();
        }

        protected override void Amend() {
            List<PriceEvaluateViewModel> selectedList = this.dgvPriceEvaluateList.GetSelectedRows<PriceEvaluateViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            PriceEvaluate priceEvaluate = this._priceEvaluateProcessor.FetchPriceEvaluateById(selectedList[0].Key);
            priceEvaluate.ClassStatus = ClassStatus.Updated;
            this.FBS.CurrentItem = priceEvaluate;
            this.gbPriceEvaluateInfo.Enabled = true;
            base.Amend();
        }

        protected override void Save() {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                PriceEvaluate priceEvaluate = this.FBS.CurrentItem;

                if (priceEvaluate.ClassStatus == ClassStatus.Added) {
                    priceEvaluate.CreatedBy = LoginUserName;
                    this._priceEvaluateProcessor.Insert(priceEvaluate);
                }
                else {
                    priceEvaluate.ModifiedBy = LoginUserName;
                    this._priceEvaluateProcessor.Update(priceEvaluate);
                }

                this.MDIParent.SetStatusInformation("保存成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Save();
            });
        }

        protected override void Delete() {
            List<PriceEvaluateViewModel> selectedList = this.dgvPriceEvaluateList.GetSelectedRows<PriceEvaluateViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._priceEvaluateProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
            });
            base.Delete();
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new PriceEvaluateSearchModel();
                }
                else {
                    this._searchModel = (PriceEvaluateSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindPriceEvaluateList();
            });
        }

        #endregion

        public FrmPriceEvaluate() {
            this.InitializeComponent();
            this.dgvPriceEvaluateList.DataGridViewModelType = typeof(PriceEvaluateViewModel);
        }

        #region Private methods

        private void ResetForms() {
            this.BindPriceEvaluateList();
            this.FBS.CurrentItem = null;
            this.gbPriceEvaluateInfo.Enabled = false;
        }

        private void CreateFormBindings() {
            this.FBS.CreateBinding(this.ddlCustomer, x => x.SelectedValueEx, y => y.CustomerId, DataSourceUpdateMode.OnPropertyChanged);
            this.FBS.CreateBinding(this.ddlProduct, x => x.SelectedValueEx, y => y.ProductId);
            this.FBS.CreateBinding(this.cmbCurrency, x => x.SelectedValue, y => y.PayCurrencyId);
            this.FBS.CreateBinding(this.cmbPayment, x => x.SelectedValue, y => y.PaymentTypeId);
            this.FBS.CreateBinding(this.tbRemarks, x => x.Text, y => y.Remarks);
            this.FBS.CreateBinding(this.tbPrice, x => x.Text, y => y.Price, z => z.ToString("G0"));
        }

        private void BindPriceEvaluateList() {
            this.CreateNewThread(() => {
                this._priceEvaluateList = this._priceEvaluateProcessor.FetchPriceEvaluateViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvPriceEvaluateList.DataSource = new SortableBindingList<PriceEvaluateViewModel>(this._priceEvaluateList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindValidation() {
            this.validator.SetType(this.tbPrice, ValidationType.Required | ValidationType.RegularExpression);
            this.validator.SetType(this.tbPrice, ValidationType.RegularExpression);
            this.validator.SetRegularExpression(this.tbPrice, "^([0-9]+.)?[0-9]+$");
            this.validator.SetRegularExpressionMessage(this.tbPrice, "单价只能由数字组成");

            this.validator.SetType(this.ddlCustomer, ValidationType.Required);
            this.validator.SetRequiredMessage(this.ddlCustomer, this.RequiredMessage);

            this.validator.SetType(this.ddlProduct, ValidationType.Required);
            this.validator.SetRequiredMessage(this.ddlProduct, this.RequiredMessage);

            this.validator.SetType(this.cmbCurrency, ValidationType.Required);
            this.validator.SetRequiredMessage(this.cmbCurrency, this.RequiredMessage);

            this.validator.SetType(this.cmbPayment, ValidationType.Required);
            this.validator.SetRequiredMessage(this.cmbPayment, this.RequiredMessage);
        }

        private void BindCustomer() {
            CustomerSearchModel searchModel = new CustomerSearchModel() { IsEnabled = true };
            CustomerProcessor customerProcessor = new CustomerProcessor();
            List<CustomerViewModel> customerList = customerProcessor.FetchCustomerViewModelList(searchModel).ToList();

            this.ddlCustomer.DisplayMemberEx = "Code";
            this.ddlCustomer.ValueMemberEx = "Key";
            this.ddlCustomer.HeightEx = 300;
            this.ddlCustomer.WidthEx = 400;
            this.ddlCustomer.PageSizeEx = 20;
            this.ddlCustomer.DataBind(new CustomerViewModel(), x => new { x.Code, x.Name, x.Address }, customerList);
        }

        private void BindProduct() {
            ProductSearchModel searchModel = new ProductSearchModel() { IsEnabled = true };
            ProductProcessor productProcessor = new ProductProcessor(int.MaxValue);
            List<ProductViewModel> productList = productProcessor.FetchProductViewModelList(searchModel).ToList();

            this.ddlProduct.DisplayMemberEx = "Code";
            this.ddlProduct.ValueMemberEx = "Key";
            this.ddlProduct.HeightEx = 300;
            this.ddlProduct.WidthEx = 400;
            this.ddlProduct.PageSizeEx = 20;
            this.ddlProduct.DataBind(new ProductViewModel(), x => new { x.Code, x.Name, x.ProductType }, productList);
        }

        #endregion

        private void FrmPriceEvaluate_Load(object sender, EventArgs e) {
            this.WindowState = FormWindowState.Maximized;
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this.FBS = new FlexBindingSource<PriceEvaluate>();

                this._priceEvaluateProcessor = new PriceEvaluateProcessor(this.pceList.PageSize);
                this._searchModel = new PriceEvaluateSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.BindBasics(this.cmbCurrency, BasicsType.Currency);
                this.BindBasics(this.cmbPayment, BasicsType.PaymentType);
                this.BindCustomer();
                this.BindProduct();
                this.BindPriceEvaluateList();
                this.CreateFormBindings();
                this.BindValidation();
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindPriceEvaluateList();
        }
    }
}
